package com.analyse.stock.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import com.analyse.stock.form.MailInfoForm;
import com.analyse.stock.model.FundTopBoardStockModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.Objects;
import java.util.Properties;

@Slf4j
public class MailUtil {

    public static void senderAsync(MailInfoForm form){
        ThreadUtil.execAsync(() -> sender(form),true);
    }

    public static boolean sender(MailInfoForm form){
        if(Objects.isNull(form) || Objects.isNull(form.getConfig())){
            return false;
        }
        if(Objects.isNull(form.getConfig().getEnable()) || !form.getConfig().getEnable()){
            log.info("## 邮箱通知未开启，不发送邮件....");
            return false;
        }
        // 邮件服务器配置
        Properties props = new Properties();
        // SMTP服务器地址
        props.put("mail.smtp.host", form.getConfig().getForm().getHost());
        // SMTP服务器端口
        props.put("mail.smtp.port", form.getConfig().getForm().getPort());
        // 是否需要身份验证
        props.put("mail.smtp.auth", "true");
        // 启用TLS加密
        props.put("mail.smtp.starttls.enable", "true");
        // 创建Session实例
        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(form.getConfig().getForm().getFromUser(),
                        form.getConfig().getForm().getFromUserPass());
            }
        });
        try {
            // 创建邮件实例
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(form.getConfig().getForm().getFromUser()));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(form.getConfig().getTo().getToUser()));
            // 邮件主题
            message.setSubject(form.getSubject());
            if(StringUtils.isNotBlank(form.getContentText())){
                message.setText(form.getContentHtml());
            }
            /*if(StringUtils.isNotBlank(form.getContentHtml())){
                // 创建消息部分
                BodyPart messageBodyPart = new MimeBodyPart();
                // 设置HTML内容
                messageBodyPart.setContent(form.getContentHtml(), "text/html");
                // 创建多部分
                Multipart multipart = new MimeMultipart();
                // 添加消息部分到多部分
                multipart.addBodyPart(messageBodyPart);
                // 设置多部分消息
                message.setContent(multipart);
            }*/
            // 发送邮件
            Transport.send(message);
            log.info("## 邮件：{} 发送成功，时间：{} ",form.getSubject(), DateUtil.now());
            return true;
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }

    public static void transHtml(MailInfoForm form,List<FundTopBoardStockModel> fundList,Integer day){
        StringBuffer sbf = new StringBuffer();
        sbf.append("<html><body><h2>").append(form.getSubject()).append("</h2>");
        sbf.append("<table border=\"1\">");
        sbf.append("<tr><th>股票名称</th><th>股票编码</th><th>最新价</th><th>涨跌幅%</th><th>换手率%</th><th>所属板块</th><th>近").append(day).append("日主力资金净流入</th></tr>");
        for(FundTopBoardStockModel stockModel : fundList){
            sbf.append("<tr>");
            sbf.append("<td>").append(stockModel.getStockName()).append("</td>");
            sbf.append("<td>").append(stockModel.getStockCode()).append("</td>");
            sbf.append("<td>").append(stockModel.getPrice()).append("</td>");
            sbf.append("<td>").append(stockModel.getUpDownPercent()).append("</td>");
            sbf.append("<td>").append(stockModel.getExchangeRate()).append("</td>");
            sbf.append("<td>").append(stockModel.getBoardName()).append("</td>");
            sbf.append("<td>").append(stockModel.getMainSumAmt()).append("</td>");
            sbf.append("</tr>");
        }
        sbf.append("</table>").append("</body></html>");
        form.setContentHtml(sbf.toString());
    }
}

